import {
  LockTwoTone,
  UserOutlined,
} from '@ant-design/icons';
import { Alert, Modal, Tabs, Form, Avatar, Radio } from 'antd';
import React, { useEffect, useState } from 'react';
import ProForm, { ProFormCheckbox, ProFormText } from '@ant-design/pro-form';
import { connect, Dispatch, useIntl, FormattedMessage } from 'umi';
import { LoginUserItemType, StateType } from '@/models/login';
import {  OnlyLoginParamsType } from '@/services/login';
import { ConnectState } from '@/models/connect';

import styles from './index.less';
import avatar from '@/assets/avatar.png';

interface LoginProps {
  dispatch: Dispatch;
  userLogin: StateType;
  submitting?: boolean;
}

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);
// 登录页面
const Login: React.FC<LoginProps> = (props) => {
  const { userLogin = {}, submitting } = props;
  const { status, users } = userLogin;
  const [visible, setVisible] = useState<boolean>(false); // 是否显示登录账号的弹窗。
  const [chooseUser, setChooseUser] = useState<LoginUserItemType | undefined>(undefined); // 设置选择的登录账号
  // 判断是否登录
  useEffect(() => {
    // console.log('【登录状态】', userLogin);
    if (users && users.length > 0) {
      setChooseUser(users[0]);
      setVisible(true);
    }
  }, [userLogin]);
  const [form] = Form.useForm(); // 表单实例
  const intl = useIntl();

  // 发送登录请求
  const handleSubmit = (values: OnlyLoginParamsType) => {
    const { dispatch } = props;
    dispatch({
      type: 'login/login',
      payload: { ...values },
    });
  };
  // 取消登录
  const cancelLogin = () => {
    setVisible(false);
    form.resetFields(); 
  }
  // 确定登录用户
  const confrimLogin = () => {
    const { dispatch } = props;
    setVisible(false);
    dispatch({
      type: 'login/chooseUser',
      payload: { 
        id: chooseUser?.uid,
        user_type: chooseUser?.type,
        token: chooseUser?.token,
       }
    })
  }
  
  return (
    <div className={styles.main}>
      <ProForm
        form={form}
        initialValues={{
          rememberPassword: true,
        }}
        submitter={{
          render: (_, dom) => dom.pop(),
          submitButtonProps: {
            loading: submitting,
            size: 'large',
            style: {
              width: '100%',
            },
          },
        }}
        onFinish={async (values) => {
          handleSubmit(values);
        }}
      >
        <Tabs>
          <Tabs.TabPane
            key="account"
            tab={intl.formatMessage({
              id: 'pages.login.accountLogin.tab',
              defaultMessage: '管理登录',
            })}
          />
        </Tabs>

        {status === 'error' && !submitting && (
          <LoginMessage
            content={intl.formatMessage({
              id: 'pages.login.accountLogin.errorMessage',
              defaultMessage: '密码错误，请输入正确密码！',
            })}
          />
        )}
        {/* 管理账号登录 */}
        <>
          <ProFormText
            name="mobile"
            fieldProps={{
              size: 'large',
              prefix: <UserOutlined className={styles.prefixIcon} />,
            }}
            placeholder={intl.formatMessage({
              id: 'pages.login.username.placeholder',
              defaultMessage: '请输入手机号',
            })}
            rules={[
              {
                required: true,
                message: (
                  <FormattedMessage
                    id="pages.login.username.required"
                    defaultMessage="请输入手机号!"
                  />
                ),
              },
            ]}
          />
          <ProFormText.Password
            name="password"
            fieldProps={{
              size: 'large',
              prefix: <LockTwoTone className={styles.prefixIcon} />,
            }}
            placeholder={intl.formatMessage({
              id: 'pages.login.password.placeholder',
              defaultMessage: '请输入登录密码',
            })}
            rules={[
              {
                required: true,
                message: (
                  <FormattedMessage
                    id="pages.login.password.required"
                    defaultMessage="请输入密码！"
                  />
                ),
              },
            ]}
          />
        </>
        <div
          style={{
            marginBottom: 24,
          }}
        >
          <ProFormCheckbox noStyle name="rememberPassword">
            <FormattedMessage id="pages.login.rememberMe" defaultMessage="记住密码" />
          </ProFormCheckbox>
          {/* <a
            style={{
              float: 'right',
            }}
          >
            <FormattedMessage id="pages.login.forgotPassword" defaultMessage="忘记密码" />
          </a> */}
          {/* 选择登录账号弹窗 */}
          <Modal
            title="选择登录账号"
            centered
            visible={visible}
            onOk={() => confrimLogin()}
            onCancel={() => cancelLogin()}
            width={1000}
          >
            <div className={styles.userList}>
              {users?.map((item, index) => { return <div
                onClick={() => setChooseUser(item)}
                className={styles.userItem} key={index}>
                  {/* 头像 */}
                  <Avatar src={avatar} size="large"/>
                  {/* 信息 */}
                  <div className={styles.userInfo}>
                    <div className={styles.userTitle}>{item.uid + "-" + item.name}</div>
                    <div className={styles.userTip}>{item.oid}</div>
                  </div>
                  <Radio checked={chooseUser && chooseUser.uid == item.uid}></Radio>
                </div>
              })}
            </div>
          </Modal>
        </div>
      </ProForm>
    </div>
  );
};

export default connect(({ login, loading }: ConnectState) => ({
  userLogin: login,
  submitting: loading.effects['login/login'],
  decisiveUse: loading.effects['login/chooseUse'],
}))(Login);
